import store from '@/store/index'
import { R } from '@/entity/R'
import { wsMessageType, wsResult } from '@/entity/ws';
export default class SocketService {

  // 初始化
  static instance: any = null;
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService();
    }
    return this.instance;
  }




  // 和服务端连接的socket对象
  ws: any = null;
  // 存储回调函数
  callBackMapping = {};
  // 标识是否连接成功
  connected = false;
  // 记录重试的次数
  sendRetryCount = 0;
  // 重新连接尝试的次数
  connectRetryCount = 0;


  //  定义连接服务器的方法

  connect() {
    // 连接服务器
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket');
    }
    let url = `ws://localhost:8848/chat/${localStorage.getItem("ws-name")}`;
    this.ws = new WebSocket(url);

    // 连接成功的事件
    this.ws.onopen = () => {
      console.log('连接服务端成功了');
      this.connected = true;
      // 重置重新连接的次数
      this.connectRetryCount = 0;
    };


    // 1.连接服务端失败
    // 2.当连接成功之后, 服务器关闭的情况
    this.ws.onclose = () => {
      console.log('连接服务端失败');
      this.connected = false;
      this.connectRetryCount++;
      setTimeout(() => {
        this.connect();
      }, 500 * this.connectRetryCount);
    };

    // 得到服务端发送过来的数据  获取系统发送的 消息
    this.ws.onmessage = (msg: R) => {
      let wsData = JSON.parse(msg.data)
      let obj: wsResult = {}
      // console.log(typeof (wsData.joinPerson), typeof (wsData.leavePerson), typeof (wsData.msg));

      if (typeof (wsData.joinPerson) === 'string') {
        obj.type = 1;
        obj.person = wsData.joinPerson
      } else if (typeof (wsData.leavePerson) === 'string') {
        obj.type = 2;
        obj.person = wsData.leavePerson
      } else if (typeof (wsData.msg) === 'string' && typeof (wsData.from) === 'string') {
        obj.type = 3;
        obj.message = wsData.msg
        obj.person = wsData.from
      }
      store.commit('websocket/setJoinPerson', obj);
      // let allMessage = store.getters['websocket/getAllMessage']
      // console.log(allMessage);
    };

  }
  // 发送数据的方法
  send(data: wsMessageType) {

    // 判断此时此刻有没有连接成功
    if (this.connected) {
      this.sendRetryCount = 0;
      try {
        this.ws.send(JSON.stringify(data));
      } catch (e) {
        this.ws.send(JSON.stringify(data));
      }
    } else {
      this.sendRetryCount++;
      setTimeout(() => {
        this.send(data);
      }, this.sendRetryCount * 500);
    }
  }

  close() {
    this.ws.close()
    this.ws.onclose = function () {
      console.log('用户主动退出！')
    }
    return true
  }


}